package com.shuwen.gcdj.service.dictionaryItem.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuwen.gcdj.bean.dictionaryItem.DictionaryItemIdNameBean;
import com.shuwen.gcdj.bean.dictionaryItem.request.*;
import com.shuwen.gcdj.bean.dictionaryItem.response.DictionaryItemListVO;
import com.shuwen.gcdj.bean.dictionaryItem.response.DictionaryItemMainVO;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.api.ResultCode;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.exception.ApiException;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.entity.Dictionary;
import com.shuwen.gcdj.entity.DictionaryItem;
import com.shuwen.gcdj.mapper.mysql.DictionaryItemMapper;
import com.shuwen.gcdj.service.dictionary.DictionaryService;
import com.shuwen.gcdj.service.dictionaryItem.DictionaryItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DictionaryItemServiceImpl extends ServiceImpl<DictionaryItemMapper, DictionaryItem> implements DictionaryItemService {

    @Autowired
    DictionaryService dictionaryService;

    @Autowired
    DictionaryItemMapper dictionaryItemMapper;

    public CommonResult<List<DictionaryItemMainVO>> getList(DictionaryItemMainParam param) {
        return CommonResult.success(dictionaryItemMapper.getList(param));
    }

    public CommonResult<List<DictionaryItemListVO>> getListByIds(DictionaryItemListParam param) {

        List<String> itemIds = new ArrayList<>();
        for (String itemId : param.getItemIds().stream().distinct().collect(Collectors.toList())) {
            if (itemId.length() > 36) {
                String[] strArr = itemId.split(",");
                for (String value : strArr) {
                    if (!StringUtils.isEmpty(value)) {
                        itemIds.add(value);
                    }
                }
            } else {
                itemIds.add(itemId);
            }
        }
        List<DictionaryItem> dictionaryItemList = list(new LambdaQueryWrapper<DictionaryItem>().in(DictionaryItem::getId, itemIds));
        List<DictionaryItemListVO> dictionaryItemListVOList = new ArrayList<>();
        if (dictionaryItemList.isEmpty()) {
            return CommonResult.success(dictionaryItemListVOList);
        }
        Map<String, String> areaMap = new HashMap<>();
        for (DictionaryItem area : dictionaryItemList) {
            areaMap.put(area.getId(), area.getName());
        }
        if (!dictionaryItemList.isEmpty()) {
            for (String itemId : param.getItemIds().stream().distinct().collect(Collectors.toList())) {
                List<String> areaName = new ArrayList<>();
                String[] strArr = itemId.split(",");
                for (String value : strArr) {
                    if (!StringUtils.isEmpty(value) && areaMap.get(value) != null) {
                        areaName.add(areaMap.get(value));
                    }
                }
                if (!areaName.isEmpty()) {
                    DictionaryItemListVO dictionaryItemListVO = new DictionaryItemListVO();
                    dictionaryItemListVO.setId(itemId);
                    dictionaryItemListVO.setName(String.join(",", areaName));
                    dictionaryItemListVOList.add(dictionaryItemListVO);
                }
            }
        }
        return CommonResult.success(dictionaryItemListVOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<DictionaryItemMainVO> add(DictionaryItemAddParam param, InitUserDto initUserDto) {
        DictionaryItem dictionaryItem = new DictionaryItem();
        dictionaryItem.setLevel(Constants.ADD_TYPE_NORMAL_ADD);
        dictionaryItem.setCreateId(initUserDto.getUserId());
        dictionaryItem.setCreateDeptId(initUserDto.getDeptId());
        dictionaryItem.setUpdateId(initUserDto.getUserId());
        BeanUtils.copyProperties(param, dictionaryItem);
        DictionaryItem parentItem = param.getParentId() != null ? getById(param.getParentId()) : null;
        if (parentItem != null) {
            dictionaryItem.setLevel(parentItem.getLevel() + 1);
            dictionaryItem.setPath(parentItem.getPath() + parentItem.getId() + ',');
        }
        boolean result = save(dictionaryItem);
        if (!result) {
            throw new ApiException(ResultCode.FAILED);
        }
        DictionaryItemMainVO dictionaryItemMainVO = new DictionaryItemMainVO();
        BeanUtils.copyProperties(getById(dictionaryItem.getId()), dictionaryItemMainVO);
        return CommonResult.success(dictionaryItemMainVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<DictionaryItemMainVO> update(DictionaryItemUpdateParam param, InitUserDto initUserDto) {
        if (getById(param.getId()) == null) {
            throw new ApiException(ResultCode.VALIDATE_FAILED);
        }
        DictionaryItem dictionaryItem = new DictionaryItem();
        dictionaryItem.setUpdateId(initUserDto.getUserId());
        BeanUtils.copyProperties(param, dictionaryItem);
        boolean result = updateById(dictionaryItem);
        if (!result) {
            throw new ApiException(ResultCode.FAILED);
        }
        DictionaryItemMainVO dictionaryItemMainVO = new DictionaryItemMainVO();
        BeanUtils.copyProperties(getById(dictionaryItem.getId()), dictionaryItemMainVO);
        return CommonResult.success(dictionaryItemMainVO);

    }

    @Override
    public Boolean batchSave(DictionaryItemBatchSaveParam param, InitUserDto initUserDto) {
        Dictionary dictionary = dictionaryService.getById(param.getDictionaryId());
        if (dictionary == null) {
            throw new ApiException(ResultCode.VALIDATE_FAILED);
        }
        dictionary.setUpdateId(initUserDto.getUserId());
        StringBuilder addItemList = new StringBuilder();
        StringBuilder editItemList = new StringBuilder();
        StringBuilder banItemList = new StringBuilder();
        for (DictionaryItemIdNameBean item : param.getItems()) {
            DictionaryItem dictionaryItem = new DictionaryItem();
            DictionaryItem existDictionaryItem = null;
            if (!StringUtils.isEmpty(item.getId())) {
                existDictionaryItem = getById(item.getId());
            }
            if (!StringUtils.isEmpty(item.getId()) && existDictionaryItem != null) {
                BeanUtils.copyProperties(item, dictionaryItem);
                if (!existDictionaryItem.getName().equals(item.getName())) {
                    editItemList.append("\"" + item.getName() + "\"");
                }
                if (!existDictionaryItem.getStatus().equals(item.getStatus()) && item.getStatus().equals(0)) {
                    banItemList.append("\"" + item.getName() + "\"");
                }
            } else {
                BeanUtils.copyProperties(item, dictionaryItem, "id");
                addItemList.append("\"" + item.getName() + "\"");
            }
            dictionaryItem.setDictionaryId(param.getDictionaryId());
            saveOrUpdate(dictionaryItem);
        }
        return true;
    }

    @Override
    public  CommonResult<String>  deletes(String ids,InitUserDto initUserDto){
        String[] id=ids.split(",");
        for (String s : id) {
         dictionaryItemMapper.update(null, new UpdateWrapper<DictionaryItem>().lambda()
                 .eq(DictionaryItem::getId, s)
                 .set(DictionaryItem::getIsDelete, Constants.IS_DELETE_YES)
                 .set(DictionaryItem::getUpdateId,initUserDto.getUserId()));
        }
        return CommonResult.success("");
    }

}
